﻿public class Solution {
    public int MaxProfit(int[] prices)
    {
        if (prices is null || prices.Length == 0) return 0;
        // 持有状态，今日卖出，冻结，保持卖出
        int[,] dp = new int[prices.Length, 4];
        dp[0, 0] = -prices[0];
        
        // 状态转移
        for (int i = 1; i < prices.Length; i++)
        {
            dp[i, 0] = new [] {dp[i - 1, 0], dp[i - 1, 2] - prices[i], dp[i - 1, 3] - prices[i]}.Max();
            dp[i, 1] = dp[i - 1, 0] + prices[i];
            dp[i, 2] = dp[i - 1, 1];
            dp[i, 3] = Math.Max(dp[i - 1, 3], dp[i - 1, 2]);
        }
        return new [] {dp[prices.Length - 1, 1], dp[prices.Length - 1, 2], dp[prices.Length - 1, 3]}.Max();
    }

    public static void Main(string[] args)
    {
        int[] prices = [1, 2, 3, 0, 2];
        Solution solution = new Solution();
        int res = solution.MaxProfit(prices);
        Console.WriteLine(res);
    }
}